/*
 * 设计方案类
 * @version: 1.0
 * @modify : 2023-07-24
 */
import { Element } from './element'
import { Variable } from './variable'
import fs from '@ohos.file.fs';

export class Scheme {
  public name:string //方案名
  public data: Map<String, Variable>
  public layout: Array<Element>
  public used: Array<string>
  constructor(name?: string, data?: Map<String, Variable>, layout?: Array<Element>, used?: Array<string>) {
    if (name) {
      this.name = name;
    }
    if (data) {
      this.data = data;
    }else this.data = new Map<String, Variable>()
    if (layout) {
      this.layout = layout;
    }
    if (used) {
      this.used = used;
    }

  }
  /**
   * 通过方案名从文件中加载对应的设计方案
   * @param name 方案名
   * @returns 设计方案
   */
  static loadScheme(name: string,dirPath:string):Scheme{
      //todo
    Scheme.getSchemesFromStorage(dirPath).forEach((scheme)=>{
      if(name==scheme.name){
        return scheme
      }
    })
      return null
  }
  /**
   * 获取系统中存储的所有设计方案的方案名
   * @returns
   */
  static getSchemesNameFromStorage(dirPath:string):Array<string>{
    //todo
    let filenames = fs.listFileSync(dirPath);
    return filenames
  }
  /**
   * 获取系统中存储的所有设计方案
   * @returns
   */
  static getSchemesFromStorage(dirPath:string):Array<Scheme>{
    let schemes: Array<Scheme> = []
    let buf = new ArrayBuffer(4096)
    let file = null
    let jsonString:string = ""
    Scheme.getSchemesNameFromStorage(dirPath).forEach((name)=>{
      file = fs.openSync(dirPath+name,fs.OpenMode.READ_WRITE)
      fs.read(file.fd,buf,(err,readLen)=>{
        if (err) {
          console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code);
        } else {
          console.info("read file data succeed");
          jsonString = String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))
          let scheme = JSON.parse(jsonString)
          schemes.push(scheme)
          fs.closeSync(file);
        }
      })
    })
    return schemes
  }

  /**
   * 将方案保存到文件中
   */
  save(dirPath:string):void{
    //todo
    let scheme = new Scheme(this.name,this.data,this.layout,this.used)
    let filePath = dirPath + "/" + this.name + ".json"
    let jsonString = JSON.stringify(scheme)
    let file = fs.openSync(filePath,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    fs.write(file.fd,jsonString,(err, writeLen) => {
      if (err) {
        console.info("write failed with error message: " + err.message + ", error code: " + err.code);
      } else {
        console.info("write data to file succeed and size is:" + writeLen);
        fs.closeSync(file);
      }
    })
  }
}
